package com.centit.framework.ip.util;

import com.alibaba.fastjson.JSONObject;
import com.centit.framework.system.po.UserInfo;
import com.centit.framework.system.po.UserRole;
import com.centit.framework.system.po.UserUnit;
import com.centit.support.algorithm.UuidOpt;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ClientRequestUtil {

    private List<Object> paramsList;

    public ClientRequestUtil() {
        this.paramsList = new ArrayList<Object>();
    }

    /**
     * 解析出url参数中的键值对
     * 如 "index.jsp?Action=del&id=123"，解析出Action:del,id:123存入map中
     *
     * @param URL url地址
     * @return url请求参数部分
     */
    public static Map<String, String> URLRequest(String URL) {
        Map<String, String> mapRequest = new HashMap<String, String>();
        String[] arrSplit = null;
        String strUrlParam = TruncateUrlPage(URL);
        if (strUrlParam == null) {
            return mapRequest;
        }
        //每个键值为一组
        arrSplit = strUrlParam.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");
            //解析出键值
            if (arrSplitEqual.length > 1) {
                //正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
            } else {
                if (arrSplitEqual[0] != "") {
                    //只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }

    /**
     * 去掉url中的路径，留下请求参数部分
     *
     * @param strURL url地址
     * @return url请求参数部分
     */
    private static String TruncateUrlPage(String strURL) {
        String strAllParam = null;
        String[] arrSplit = null;

        strURL = strURL.trim();
        arrSplit = strURL.split("[?]");
        if (strURL.length() > 0) {
            if (arrSplit.length > 0) {
                if (arrSplit[0] != null) {
                    strAllParam = arrSplit[0];
                }
            }
        }
        return strAllParam;

    }

    public static void main(String[] args) {
        Map<String,Object> paramsMap = new HashMap<String,Object>();
        //用户信息（必需）
        UserInfo userInfo = new UserInfo();
        userInfo.setIsValid("T");
        userInfo.setLoginName("9527");
        userInfo.setUserName("测试用户");
        userInfo.setUserNamePinyin("ceshiyonghu");
        userInfo.setUserPwd("000000");
        userInfo.setPrimaryUnit("150");//主机构代码
        paramsMap.put("userInfo",userInfo);
        //配置用户主机构信息（必需）
        UserUnit userUnit = new UserUnit();
        userUnit.setUserRank("KY");//职务，字典项RankType
        userUnit.setUserStation("ZZ");//岗位，字典项StationType
        userUnit.setIsPrimary("T");//是否主处室
        paramsMap.put("userUnit",userUnit);
        //配置用户其他机构信息
        List<UserUnit> userUnits = new ArrayList<UserUnit>();
        userUnit = new UserUnit();
        userUnit.setUnitCode("190");
        userUnit.setUserRank("KZ");//职级，字典项RankType
        userUnit.setUserStation("ZR");//职务，字典项StationType
        userUnit.setIsPrimary("F");//是否主处室
        userUnits.add(userUnit);
        //...
        paramsMap.put("userUnits",userUnits);
        //配置用户角色信息
        List<UserRole> userRoles = new ArrayList<UserRole>();
        UserRole userRole = new UserRole();
        userRole.setRoleCode("0100");
        userRoles.add(userRole);
        paramsMap.put("userRoles",userRoles);
        //发起请求
        ClientRequestUtil requestUtil = new ClientRequestUtil();
        requestUtil.addParams(paramsMap);//填充请求参数信息
        //masterPath为配置文件中配置的支撑平台地址：http://demo.centit.com/centit-ip
//        String result = requestUtil.postForObject(CodeRepositoryUtil.getSysConfigValue("masterPath") +"/system/webservice/businessData/saveUser");
        String result = requestUtil.postForObject("http://localhost/centit-ip/system/webservice/businessData/saveUser");
        System.err.println("接口响应信息：" + result);
    }

    /**
     * 添加请求参数
     *
     * @param obj
     */
    public void addParams(Object obj) {
        this.paramsList.add(obj);
    }

    /**
     * 子系统请求支撑平台接口
     *
     * @param url 接口地址
     * @return
     */
    public String postForObject(String url) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.add("X-Auth-Token", UuidOpt.getUuidAsString32());
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        HttpEntity<String> requestEntity = new HttpEntity<String>(
                JSONObject.toJSONString(this.paramsList), headers);
        String result = ClientRequestUtil.getRestTemplate().postForObject(url, requestEntity, String.class);
        return result;
    }
    public static RestTemplate getRestTemplate(){
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(3000);
        httpRequestFactory.setConnectTimeout(3000);
        httpRequestFactory.setReadTimeout(3000);
        return new RestTemplate(httpRequestFactory);
    }
}
